package middleware

import (
	"fmt"
	"gitee.com/git_public/vfaith/builtin/shape"
	"gitee.com/git_public/vfaith/fount/handle"
	"gitee.com/git_public/vfaith/sugar"
	"log"
	"math"
	"net/http"
)

func initFormHandler(w http.ResponseWriter, r *http.Request) *handle.FormHandler {
	_ = r.ParseForm()
	_ = r.ParseMultipartForm(math.MaxInt64)
	bHttp := handle.NewBlendHttp(w, r)

	fMap := shape.NewMap()
	for key, values := range r.Form {
		if len(values) > 0 {
			fMap.Add(key, values[0])
		}
	}

	isExport, _ := sugar.ToInteger(r.FormValue("isExport"))
	handler := &handle.FormHandler{
		BlendHttp: bHttp,
		Map:       fMap,
		IsExport:  isExport > 0,
	}

	return handler
}

func HttpContextForm(next func(handler *handle.FormHandler) error) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		formHandler := initFormHandler(w, r)
		if formHandler == nil {
			return
		}

		err := next(formHandler)
		if err != nil {
			log.Print(err)
			http.Error(w, fmt.Sprintf("Internal Server Error：【%s】", err), http.StatusInternalServerError)
		}
	}
}

func HttpContextFormNoError(next func(handler *handle.FormHandler)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		formHandler := initFormHandler(w, r)
		if formHandler == nil {
			return
		}

		next(formHandler)
	}
}
